// Helper for input operations.

#include "InputHelper.h"

// Construct InputHelper.
InputHelper::InputHelper()
{
}

// Construct InputHelper with given options.
InputHelper::InputHelper(InputOptions& inputOptions)
{
	ConvertToAbsoluteCoordinates(inputOptions.clickCoordinates);
	m_cursorCoordinateX = inputOptions.clickCoordinates.x;
	m_cursorCoordinateY = inputOptions.clickCoordinates.y;
	Sensibility = inputOptions.sensibility;
	m_hWnd = FindWindowW(_W("Archeage").c_str(), NULL);
}

// Set the cursor position.
void InputHelper::SetCursorPosition()
{
	INPUT Input={0};

	Input.type = INPUT_MOUSE;
	Input.mi.dx = m_cursorCoordinateX;
	Input.mi.dy = m_cursorCoordinateY;
	Input.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE;
	SendInput(1, &Input, sizeof(INPUT));
}

// Try to get the cursor position.
bool InputHelper::GetCursorPosition(POINT& coordinates)
{
	return GetCursorPos(&coordinates) != 0;
}

// Do a left click.
void InputHelper::LeftClick()
{
	INPUT Input={0};

	Input.type = INPUT_MOUSE;
	Input.mi.dwFlags = MOUSEEVENTF_LEFTDOWN;
	SendInput(1, &Input, sizeof(INPUT));

	ZeroMemory(&Input, sizeof(INPUT));
	Input.type = INPUT_MOUSE;
	Input.mi.dwFlags = MOUSEEVENTF_LEFTUP;
	SendInput(1, &Input, sizeof(INPUT));
}

// Check if a pixel color match the sensibility.
bool InputHelper::CheckPixel(const POINT& coordinates)
{
	HDC hdc = GetDC(m_hWnd);
	COLORREF pixel = GetPixel(hdc, coordinates.x, coordinates.y);
	ReleaseDC(m_hWnd, hdc);
	return GetRValue(pixel) > Sensibility && GetGValue(pixel) > Sensibility && GetBValue(pixel) > Sensibility;
}

// Convert to absolute coordinates.
void InputHelper::ConvertToAbsoluteCoordinates(POINT& coordinates)
{
	coordinates.x = (coordinates.x * 65536) / GetSystemMetrics(SM_CXSCREEN);
	coordinates.y = (coordinates.y * 65536) / GetSystemMetrics(SM_CYSCREEN);
}